package com.mobi.Survey.lib.model;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.mobi.Survey.lib.uicomponents.ControlFactory;
import com.mobi.Survey.lib.utils.Device;

public class WebServiceIO {

	private static final int CONNECTION_TIMEOUT = 10000; /* 10 seconds */

	private static final int SOCKET_TIMEOUT = 10000; /* 10 seconds */

	private static final long MCC_TIMEOUT = 10000; /* 10 seconds */

	public static boolean sendToWSBulk(String url, String userId, long surveyId, List<SurveyDetailPojo> surveyDetails) throws JSONException, Exception {
		boolean successful = false;

		HttpParams params = new BasicHttpParams();
		params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(20));
		params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 200);
		params.setLongParameter(ConnManagerPNames.TIMEOUT, 10);

		params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
		params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT);
		params.setLongParameter(ConnManagerPNames.TIMEOUT, MCC_TIMEOUT);
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

		HttpClient client = new DefaultHttpClient(params);

		HttpResponse response;

		JSONArray jsonArray = new JSONArray();
	 
			HttpPost post = new HttpPost(url);

			System.out.println("sendToWSBulk Connecting Localhost......");

			for (SurveyDetailPojo sdp : surveyDetails) {
				if (sdp.isSaveAble() && sdp.getUserValue() != null && sdp.getUserValue().trim().length() > 0) {

					int controlType = (int) sdp.getControlType();
					int seqNum = (int) sdp.getSequanceNo();
					int subscriptionId = (int) sdp.getSubscriptionId();
 
					String deviceNumber = SurveyDetailPojo.getDeviceId();
					String userValueIn = sdp.getUserValue();// SJ
					 
					String userValue = "";
					String[] userValueArray = null;
					int userValueArrayCount = 1;
					boolean singleValue = true;
					switch (sdp.getControlType()) {
					case ControlFactory.CONTROL_DATE:
						userValue = userValueIn.replaceAll("\\|", "-");
						break;
					case ControlFactory.CONTROL_TIME:
						userValue = userValueIn.replaceAll("\\|", ":");
						break;
					case ControlFactory.CONTROL_CHECK_BOX:
						String delimiter = "\\|";
						userValueArray = userValueIn.split(delimiter);
						userValueArrayCount = userValueArray.length;
						singleValue = false;
						break;
					default:
						userValue = userValueIn;
						break;
					}
					if (singleValue) {
						userValueArray = new String[1];
						userValueArray[0] = userValue;
					}

					for (int i = 0; i < userValueArrayCount; i++) {
						JSONObject json = new JSONObject();
						if (userValueArray[i] != null && userValue != null) {
							json.put("surveyId", surveyId);
							json.put("userId", userId);
							json.put("controlType", controlType);
							json.put("seqNum", seqNum);
							json.put("subscriptionId", subscriptionId);
							json.put("deviceNumber", deviceNumber);
							json.put("userValue", userValueArray[i]);
				
							jsonArray.put(json);
						}// if
					}

				} 
			} 

			System.out.println("results bulk jsonArray=" + jsonArray.toString());
			JSONObject json1 = new JSONObject();
			json1.put("jsonData", jsonArray);
			System.out.println("results json1=" + json1.toString());
			StringEntity se = new StringEntity(json1.toString(), "UTF-8");
			se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json; charset=UTF-8"));
			post.setEntity(se);
			post.setHeader("User-Agent", "BizFinder User Agent");
			response = client.execute(post);
			String results = response.getStatusLine().toString();
			System.out.println("Response Result: " + results);
			int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode == 200) {
				successful = true;
			} else if (statusCode != 200) {
				successful = false;
			}

			successful = true;
		 

		return successful;
	}

	public static final boolean submitTimerStatus(String url, String userId, byte result, AlarmPojo attr) {
		boolean successful = false;
		HttpParams params = new BasicHttpParams();
		params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(20));
		params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 200);
		params.setLongParameter(ConnManagerPNames.TIMEOUT, 10);

		params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
		params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT);
		params.setLongParameter(ConnManagerPNames.TIMEOUT, MCC_TIMEOUT);
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

		HttpClient client = new DefaultHttpClient(params);

		HttpResponse response;

		try {
			Device.getInstance();
			String deviceNumber = Device.getDeviceId();

			StringBuilder query = new StringBuilder();
			query.append("?").append("formId=").append(attr.getSurveyId()).append("&")

			.append("controlType=").append(ControlFactory.CONTROL_TIMER)

			.append("&").append("result=").append(result)

			.append("&").append("formDetailsPK=").append(attr.getSequanceNo())

			.append("&").append("repeatInterval=").append(attr.getRepeatType())

			.append("&").append("userid=").append(userId)

			.append("&").append("devicenumber=").append(deviceNumber);

			HttpGet get = new HttpGet(url + query.toString());

			get.setHeader("User-Agent", "BizFinder User Agent");
			response = client.execute(get);
			String results = response.getStatusLine().toString();
			System.out.println("Timer Submit Result" + results);
			successful = true;
		} catch (UnsupportedEncodingException e) {
		 
			e.printStackTrace();
			successful = false;
		} catch (ClientProtocolException e) {
		 
			e.printStackTrace();
		} catch (IOException e) {
			 
			e.printStackTrace();
			successful = false;
		}

		return successful;
	}

	/**
	 * 
	 * @param surveyDetails
	 * @param surveyId
	 * @return true if result submitted successfully
	 * @throws Exception 
	 * @throws JSONException 
	 */
	public static final boolean submitResult(String url, String userId, long surveyId, List<SurveyDetailPojo> surveyDetails) throws JSONException, Exception {

		return sendToWSBulk(url, userId, surveyId, surveyDetails);

	}

	// Web service code segment to retrive aggregate result for surveyKey
	public static List<AggregateResultPojo> getAggregateResult(long surveyId, String sKey) {

		return null;
	}

	/**
	 * 
	 * Web service code to retrive survey for the surveyKey and return
	 * SurveyPojo
	 * 
	 * @param surveyKey
	 * @return SurveyPojo
	 */
	public static SurveyPojo getSurvey(String surveyKey) {

		return null;
	}
}
